package dev.entao.core.slices

import dev.entao.base.DateX
import dev.entao.base.MIN
import dev.entao.core.HttpService
import dev.entao.core.HttpSlice
import dev.entao.log.LogX
import dev.entao.log.loge
import java.util.*


interface HttpTimer {
	//hour [0-23]
	fun onHour(h: Int) {}

	//m一直自增 , 会大于60
	fun onMinute(m: Int) {}

	//dayOfMonth [0-31]
	//hour [0-23]
	//minute [0-59]
	fun onHttpTimer(dayOfMonth: Int, hour: Int, minute: Int)
}


class TimerSlice(callback: HttpTimer) : HttpSlice {


	private var httpService: HttpService? = null
	private var timer: Timer? = null
	private val timerList = ArrayList<HttpTimer>()

	init {
		timerList += callback
	}

	fun addTimer(t: HttpTimer) {
		if (t !in this.timerList) {
			this.timerList += t
		}
	}

	override fun onInit(httpService: HttpService) {
		this.httpService = httpService
		timer?.cancel()
		timer = null
		val tm = Timer("everyMinute", true)
		val delay: Long = 1.MIN
		tm.scheduleAtFixedRate(tmtask, delay, delay)
		timer = tm
	}

	override fun onDestory(httpService: HttpService) {
		timer?.cancel()
		timer = null
		timerList.clear()
		this.httpService = null
	}

	private val tmtask = object : TimerTask() {

		private var minN: Int = 0
		private var preHour = -1

		override fun run() {
			val date = DateX()
			val day = date.day
			val h = date.hour
			val minute = date.minute
			val timers = ArrayList<HttpTimer>(timerList)
			timers.forEach {
				try {
					it.onHttpTimer(day, h, minute)
				} catch (ex: Exception) {
					ex.printStackTrace()
				}
			}

			if (h != preHour) {
				preHour = h
				for (ht in timers) {
					try {
						ht.onHour(h)
					} catch (ex: Exception) {
						loge(ex)
					}
				}
			}

			val n = minN++
			for (mt in timers) {
				try {
					mt.onMinute(n)
				} catch (ex: Exception) {
					loge(ex)
				}
			}

			try {
				LogX.flush()
			} catch (ex: Exception) {
			}
			httpService?.cleanThreadLocals()
		}
	}

}
